package common

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"

	"go-papers/models"
	"go-papers/tools"
	"go-papers/tools/app"
	"go-papers/tools/app/msg"
)

func GetCommonCfgList(c *gin.Context) {
	var data models.CommonCfg
	var err error

	data.CfgCode = c.Request.FormValue("cfgCode")
	data.CfgName = c.Request.FormValue("cfgName")
	data.CfgVal = c.Request.FormValue("cfgVal")

	data.DataScope = tools.GetUserIdStr(c)
	result, err := data.GetListInfo()
	if err != nil {
		app.ApiResp(c, -1, "数据记录不存在："+err.Error(), nil)
		return
	}

	var resp = make(map[string]interface{})
	resp["list"] = result

	var info = make(map[string]interface{})
	if len(result) > 0 {
		for _, v := range result {
			info[v.CfgCode] = v.CfgVal
		}
	}
	resp["data"] = info
	app.CommonResp(c, 0, "成功", resp)
}

func UpdateCommonCfgList(c *gin.Context) {
	var data models.CommonCfgData
	var cfgInfo models.CommonCfg

	err := c.ShouldBindJSON(&data)
	if err != nil {
		app.CommonResp(c, -1, "参数异常："+err.Error(), nil)
		return
	}
	cfgInfo.UpdateBy = tools.GetUserIdStr(c)

	cfgInfo.CfgVal = data.OrganRate
	_, _ = cfgInfo.UpdateByCode("organ_rate")

	cfgInfo.CfgVal = data.MomRate
	_, _ = cfgInfo.UpdateByCode("mom_rate")

	cfgInfo.CfgVal = data.MemberNums
	_, _ = cfgInfo.UpdateByCode("member_nums")

	cfgInfo.CfgVal = data.MomExtraRate
	_, _ = cfgInfo.UpdateByCode("mom_extra_rate")

	cfgInfo.CfgVal = data.MomExtraMax
	_, _ = cfgInfo.UpdateByCode("mom_extra_max")

	app.CommonResp(c, 0, "成功", data)
}

func GetCommonCfg(c *gin.Context) {
	var data models.CommonCfg
	data.CfgId, _ = tools.StringToInt(c.Param("cfgId"))
	result, err := data.Get()
	if err != nil {
		app.ApiResp(c, -1, "数据记录不存在："+err.Error(), nil)
		return
	}
	app.OK(c, result, "")
}

func InsertCommonCfg(c *gin.Context) {
	var data models.CommonCfg
	err := c.ShouldBindJSON(&data)
	if err != nil {
		app.ApiResp(c, -1, "数据解析异常："+err.Error(), nil)
		return
	}

	data.CreateBy = tools.GetUserIdStr(c)
	result, err := data.Create()
	if err != nil {
		app.ApiResp(c, -1, "插入失败："+err.Error(), nil)
		return
	}
	app.OK(c, result, "")
}

func UpdateCommonCfg(c *gin.Context) {
	var data models.CommonCfg
	err := c.BindWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析异常："+err.Error(), nil)
		return
	}
	result, err := data.Update(data.CfgId)
	if err != nil {
		app.ApiResp(c, -1, "数据更新失败："+err.Error(), data)
		return
	}
	app.OK(c, result, "")
}

func DeleteCommonCfg(c *gin.Context) {
	var data models.CommonCfg

	IDS := tools.IdsStrToIdsIntGroup("cfgId", c)
	_, err := data.BatchDelete(IDS)
	if err != nil {
		app.ApiResp(c, -1, "数据异常："+err.Error(), nil)
		return
	}
	app.OK(c, nil, msg.DeletedSuccess)
}
